#include"SeqList.h"

void SLcheckcapacity(SL* ps)
{
    if(ps->size ==ps->capacity)
    {
        //int newcapacity = ps->capacity * 2; 
        int newcapacity = ps->capacity == 0 ? 4 :ps->capacity * 2;
        SLDateType* tem = (SLDateType*)realloc(ps->a, sizeof(SLDateType)* newcapacity);
        if(tem == NULL)
        {
            printf("realloc fail\n");
            exit(-1);
        }
        ps->a = tem;
        ps->capacity = newcapacity;
    }
}
void SeqListInit(SL* ps)
{
    assert(ps);
    ps->a = NULL;
    ps->capacity = ps->size = 0;
}
void SLPushBack(SL* ps, SLDateType x)
{
    assert(ps);
    //SLcheckcapacity(ps);
    //ps->a[ps->size] = x;
    //ps->size++;
    
    //复用
    SLInsert(ps, ps->size, x);
}
void SLprintf(SL* ps)
{
    assert(ps);
    int i = 0;
    for(i = 0; i < ps->size; i++)
    {
        printf("%d ",ps->a[i]);
    }
    printf("\n");
}
void SLPushFront(SL* ps, SLDateType x)
{
    assert(ps);
  //  SLcheckcapacity(ps);
  //  int end = ps->size - 1;
  //  while(end >= 0)
  //  {
  //      ps->a[end + 1] = ps->a[end];
  //      end--;
  //  }
  //  ps->a[0] = x;
  //  ps->size++;
  //
  SLInsert(ps, 0, x);
}
void SLPopBack(SL* ps)
{
    assert(ps);
  //  assert(ps->size > 0);
  //  ps->size--;
    SLErase(ps,ps->size - 1);
}
void SLPopFront(SL* ps)
{
    assert(ps);
    assert(ps->size > 0);

   // int begin = 0;
   // while(begin < ps->size)//会越界
   // while(begin < ps->size - 1)
   // {
   //     ps->a[begin] = ps->a[begin + 1];
   //     begin++;
   // }
   //
   //
   //
   //
  // int begin = 1;
  // while(begin < ps->size)
  // {
  //     ps->a[begin - 1] = ps->a[begin];
  //     begin++;
  // }
  //  ps->size--;
  //
  //
  //
    SLErase(ps, 0);
}
void SLDestory(SL* ps)
{
    assert(ps);
    if(ps->a)
    {
        free(ps->a);
        ps->a = NULL;
        ps->size = ps->capacity = 0;
    }
}
void SLInsert(SL* ps, int pos,SLDateType x)
{
    assert(ps);
    //assert(pos >= 0 && pos < ps->size);
    assert(pos >= 0 && pos <= ps->size);
    SLcheckcapacity(ps);

    int end = ps->size - 1;
    while(end >= pos)
    {
        ps->a[end + 1] = ps->a[end];
        end--;
    }
    ps->a[pos] = x;
    ps->size++;
}
void SLErase(SL* ps, int pos)
{
    assert(ps);
    assert(pos >= 0 && pos < ps->size);
    int begin = pos;
    while(begin < ps->size - 1)
    {
        ps->a[begin] = ps->a[begin + 1];
        begin++;
    }
    ps->size--;

}
int SLFind(SL* ps, SLDateType x)
{
    int i = 0;
    for(i = 0; i < ps->size; i++)
    {
        if(ps->a[i] == x)
        {
            return i;
        }
    }
    return -1;
}
void SLModify(SL* ps, int pos, SLDateType x)
{
    ps->a[pos] = x;
}
